package com.waimai.admin.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.waimai.db.entity.Admin;
import com.waimai.db.entity.Category;
import com.waimai.db.entity.Comment;
import com.waimai.db.entity.Food;
import com.waimai.db.entity.Order;
import com.waimai.db.entity.Restaurant;
import com.waimai.db.entity.User;
import com.waimai.db.service.AdminService;
import com.waimai.db.service.CategoryService;
import com.waimai.db.service.FoodService;
import com.waimai.db.service.OrderService;
import com.waimai.db.service.RestaurantService;
import com.waimai.db.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController {

	private static final int adminName_password_error = 0;
	private static final int success = 1;

	@Autowired
	AdminService adminService;

	@Autowired
	RestaurantService restaurantService;

	@Autowired
	UserService userService;

	@Autowired
	OrderService orderService;

	@Autowired
	CategoryService categoryService;

	@Autowired
	FoodService foodService;

	@RequestMapping("/toRegist")
	public String toRegist() {
		return "regist";
	}

	@RequestMapping("/login")
	public String login() {
		return "login";
	}

	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session) {
		session.removeAttribute("adminLogin");
		return "redirect:login";
	}

	@RequestMapping("/toIndex")
	public String toIndex() {
		return "index";
	}

	@RequestMapping("/toCommon")
	public String toCommon() {
		return "common";
	}

	@RequestMapping("/toCommon_left")
	public String toCommon_left() {
		return "common_left";
	}

	@RequestMapping("/toAdmin_top")
	public String toAdmin_top() {
		return "admin_top";
	}

	@RequestMapping("/toAdmin_left")
	public String toAdmin_left() {
		return "admin_left";
	}

	@RequestMapping("/toAdmin_right")
	public String toAdmin_right() {
		return "admin_right";
	}

	@RequestMapping("/toError")
	public String toError() {
		return "error";
	}

	@ResponseBody
	@RequestMapping("/regist")
	public int regist(Admin admin) {
		admin.setRank("普通商家");
		System.out.println("----------" + admin + "-------------");
		adminService.saveAdmin(admin);
		return success;
	}

	@ResponseBody
	@RequestMapping("/checkLogin")
	public Admin checkLogin(String adminName, String password, HttpSession session) {
		Admin admin = adminService.getAdmin(adminName, password);
		System.out.println("登陆请求：" + admin);
		if (admin == null) {
			return admin;
		} else {
			System.out.println(admin);
			session.setAttribute("adminLogin", admin);
			return admin;
		}
	}

	@RequestMapping("/toAdminManager")
	public String toAdminManager(Model model) {
		List<Admin> admins = adminService.getAdmins();
		System.out.println("------------" + admins.size());
		model.addAttribute("admins", admins);
		return "adminManager";
	}

	@RequestMapping("/toAdminUpdate")
	public String toAdminUpdate() {
		return "adminUpdate";
	}

	@RequestMapping("/adminUpdate")
	public String adminUpdate(String password, HttpSession session) {
		Admin admin = (Admin) session.getAttribute("adminLogin");
		System.out.println(password + "," + admin.getAdminId());
		adminService.updateAdmin(password, admin.getAdminId());
		return "redirect:toAdminManager";
	}

	/*****************************************************************/
	@RequestMapping("/toRestaurantManger")
	public String toRestaurantManger(Model model) {
		List<Restaurant> restaurants = restaurantService.getRestaurants();
		model.addAttribute("restaurants", restaurants);
		return "restaurantManager";
	}

	@RequestMapping("/toSaveRestaurant")
	public String toSaveRestaurant() {
		return "restaurantAddictive";
	}

	@RequestMapping(value = "/saveRestaurant", method = RequestMethod.POST)
	public String saveRestaurant(Restaurant restaurant, int adminId, Model model) {
		restaurant.setLastUpdateTime(new Date());
		System.out.println(adminId);
		Admin admin = adminService.getById(adminId);
		restaurant.setAdmin(admin);
		System.out.println("----------------" + restaurant + "-------------");
		restaurantService.save(restaurant);
		List<Admin> adminList = adminService.getAdmins();
		model.addAttribute("adminList", adminList);
		return "redirect:toRestaurantManger";
	}

	@RequestMapping("/toRestaurantUpdate")
	public String toRestaurantUpdate(int restaurantId, Model model) {
		System.out.println("-----------" + restaurantId + "--------------");
		Restaurant restaurant = restaurantService.findById(restaurantId);
		model.addAttribute("restaurant", restaurant);
		return "restaurantUpdate";
	}

	@RequestMapping(value = "/updateRestaurant", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded")
	public String updateRestaurant(int restaurantId, String restaurantName,
			String password, String photo, String address, String phone,
			int sendPrice, int deliveryPrice, int deliveryTimeArg,
			int deliveryRange, float starLevelArg, String businessTime,
			String notice, int monthSales, boolean rest, int adminId) {
		Restaurant restaurant = new Restaurant(restaurantId, restaurantName,
				password, address, phone, photo, sendPrice, deliveryPrice,
				deliveryTimeArg, deliveryRange, starLevelArg, notice,
				monthSales, rest);
		restaurant.setLastUpdateTime(new Date());
		Admin admin = adminService.getById(adminId);
		restaurant.setAdmin(admin);
		restaurantService.update(restaurant);
		return "redirect:toRestaurantManger";
	}

	/********************************************************************/
	@RequestMapping("/toUserManager")
	public String toUserManager(Model model) {
		List<User> users = userService.getUsers();
		model.addAttribute("users", users);
		return "userManager";
	}

	@RequestMapping("/toUserOrder")
	public String toUserOrder(int userId, Model model) {
		System.out.println(userId);
		List<Order> orders = orderService.getUserOrders(userId);
		model.addAttribute("orders", orders);
		System.out.println(orders.size());
		return "orderManager";
	}

	@RequestMapping("/toUserAddress")
	public String toUserAddress(Model model) {
		List<Map<String, Object>> receiveAddresses = userService
				.getReceiveAddresses();
		model.addAttribute("receiveAddresses", receiveAddresses);
		System.out.println("-----------" + receiveAddresses.size()
				+ "--------------");
		return "userAddress";
	}

	@RequestMapping("/toUserComment")
	public String toUserComment(int userId, Model model) {
		List<Map<String, Object>> commentList = userService
				.getCommentsByUserId(userId);
		model.addAttribute("commentList", commentList);
		return "userComment";
	}

	/********************************************************************/
	@RequestMapping("/toCommResManager")
	public String toCommResManger(HttpSession session) {
		Admin admin = (Admin) session.getAttribute("adminLogin");
		session.setAttribute("adminComm", admin);
		return "commResManager";
	}

	@RequestMapping("/toCommAdminUpdate")
	public String toCommUpdate(int adminId, Model model) {
		Admin admin = adminService.getById(adminId);
		model.addAttribute("adminComm", admin);
		return "commAdminUpdate";
	}

	@RequestMapping(value = "/commAdminUpdate", method = RequestMethod.POST)
	public String commAdminUpdate(Admin admin, HttpSession session) {
		System.out.println("-------------" + admin + "-------------");
		adminService.updateAdmin(admin);
		session.setAttribute("adminComm", admin);
		return "redirect:toCommResManager";
	}

	@RequestMapping("/toCommRestaurant")
	public String toCommRestaurant(int adminId, Model model) {
		System.out.println("-----------------" + adminId
				+ "-------------------");
		List<Restaurant> restaurants = restaurantService
				.getRestaurantsByAdminId(adminId);
		model.addAttribute("restaurants", restaurants);
		return "commAdminRestaurant";
	}

	/****************************************************************/
	@RequestMapping("/toResCategory")
	public String toResCategory(int restaurantId, Model model) {
		List<Category> categories = categoryService.getCategories(restaurantId);
		model.addAttribute("categories", categories);
		return "resCategory";
	}

	@RequestMapping("/toFoodCategory")
	public String toSaveCategory(int restaurantId, Model model) {
		System.out.println("------------" + restaurantId + "----------");
		model.addAttribute("restaurantId", restaurantId);
		return "foodCategory";
	}

	@RequestMapping("saveFoodCategory")
	public String saveFoodCategory(int restaurantId, String categoryName) {
		System.out.println("------------" + restaurantId + "," + categoryName
				+ "----------");
		Category category = new Category();
		category.setCategoryName(categoryName);
		Restaurant restaurant = restaurantService.findById(restaurantId);
		category.setRestaurant(restaurant);
		categoryService.saveCategory(category);
		return "redirect:toCommResManager";
	}

	
	/********************************************************************/
	@RequestMapping("/toFoodManager")
	public String toFoodManager(Model model) {
		List<Food> foodList = foodService.foodList();
		model.addAttribute("foodList", foodList);
		return "foodManager";
	}

	@RequestMapping("/toUpdateFood")
	public String toUpdateFood(int foodId,Model model){
		Food food=foodService.getFoodById(foodId);
		model.addAttribute("food",food);
		return "foodUpdate";
	}
	
	@RequestMapping("/updateFood")
	public String updateFood(int foodId,String foodName,float price){
		Food food=foodService.getFoodById(foodId);
		food.setFoodName(foodName);
		food.setPrice(price);
		foodService.updateFood(food);
		return "redirect:toFoodManager";
	}
	
	@RequestMapping("/toFoodAddictive")
	public String toFoodAddictive(HttpSession session) {
		Admin admin=(Admin) session.getAttribute("adminLogin");
		List<Restaurant> restaurants=restaurantService.getRestaurantsByAdminId(admin.getAdminId());
		System.out.println("-----------"+restaurants.size());
		session.setAttribute("restaurants", restaurants);
		
		List<Category> categories=categoryService.getCategoriesByAdminId(admin.getAdminId());
		System.out.println("------------"+categories.size()+"-------------------");
		session.setAttribute("categories", categories);
		return "foodAddictive";
	}

	@RequestMapping("/saveFood")
	public String saveFood(String foodName, float price, String categoryName,String restaurantName) {
		Food food = new Food();
		food.setFoodName(foodName);
		food.setPrice(price);
		food.setPubTime(new Date());
		food.setMonthSales(0);
		food.setTotalSales(0);
		food.setEnabled(true);
		food.setZan(0);
		Category category = categoryService.findByCategoryName(categoryName);
		Restaurant restaurant=restaurantService.getRestaurantsByName(restaurantName);
		//保存食品
		//1、获得categoryName，找到Category,此时的Category也应该是当前admin的店铺的Category----
		//2、获得Restaurant，此时的Restaurant应该是当前店家自己的店铺---adminId
		if (category != null) {
			category.setRestaurant(restaurant);
			food.setCategory(category);
			foodService.saveFood(food);
		}
		return "redirect:toFoodManager";
	}

	/*****************************************************************/
	@RequestMapping("/toCommOrder")
	public String toCommOrder(HttpSession session) {
		Admin admin = (Admin) session.getAttribute("adminLogin");
		int adminId = admin.getAdminId();
		System.out.println("----------" + adminId + "----------");
		List<Order> orders = orderService.getOrdersByAdminId(adminId);
		System.out.println(orders.size());
		session.setAttribute("orders", orders);
		return "commOrder";
	}

	@RequestMapping("/toCommComment")
	public String toCommComment(HttpSession session) {
		Admin admin = (Admin) session.getAttribute("adminLogin");
		int adminId = admin.getAdminId();
		List<Comment> comments = restaurantService.getCommentByAdminId(adminId);
		session.setAttribute("comments", comments);
		return "commComment";
	}
	
}
